<?php
/**
 * Created by PhpStorm.
 * User: xaq
 * Date: 2017/5/23
 * Time: 15:55
 */

namespace app\api\service;


use app\lib\enum\ScopeEnum;
use app\lib\exception\ForbiddenException;
use app\lib\exception\TokenException;
use think\Cache;
use think\Request;
use think\Exception;

class Token
{
    public static function generateToken() {
        $randChars = getRandChar(32);
        $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
        //salt 盐
        $salt = config('secure.token_salt');

        return md5($randChars.$timestamp.$salt);
    }

    public static function getCurrentTokenVar($key) {
//        $token = Request::instance()
//            ->header('token');
        $token = input("post.token");
        $vars = Cache::get($token);
        if(!$vars) {
            throw new TokenException();
        }else {
            if(!is_array($vars)) {
                $vars = json_decode($vars,true);
            }
            if(array_key_exists($key, $vars)) {
                return $vars[$key];
            }else {
                throw new Exception('尝试获取的token变量并不存在');
            }
        }
    }

    public static function getCurrentUid() {
        //token
        $uid =self::getCurrentTokenVar('uid');
        return $uid;
    }

    public static function getCurrentScope() {
        //scope
        $scope = self::getCurrentTokenVar('scope');
        return $scope;
    }
    //权限属于用户和CMS超级管理员
    public static function needPrimaryScope() {
        $scope = self::getCurrentScope();
        if($scope) {
            if($scope >= ScopeEnum::User) {
                return true;
            }else{
                throw new ForbiddenException();
            }
        }else{
            throw new TokenException();
        }
    }
    //权限只属于用户
    public static function needExclusiveScope() {
        $scope = self::getCurrentScope();
        if($scope) {
            if($scope == ScopeEnum::User) {
                return true;
            }else{
                throw new ForbiddenException();
            }
        }else{
            throw new TokenException();
        }
    }
    //检测当前用户的uid是否有效
    public static function isValidOperate($checkedID) {
        if(!$checkedID) {
            throw new Exception('检查UID时必须传入一个被检查的UID');
        }
        $currentOperateUID = self::getCurrentUid();
        if($currentOperateUID == $checkedID) {
            return true;
        }else{
            return false;
        }
    }

}